package logic

import (
	"context"
	"net/http"

	"yookie.me/pdfreader/internal/svc"
	"yookie.me/pdfreader/internal/types"
	"yookie.me/pdfreader/thirdparty/tika"

	"github.com/jinzhu/copier"
	"github.com/zeromicro/go-zero/core/logx"
)

type PdfreaderLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
	client *tika.TikaClient
}

func NewPdfreaderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PdfreaderLogic {
	return &PdfreaderLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
		client: tika.NewTikaClient(svcCtx.Config.TikaHost),
	}
}

func (l *PdfreaderLogic) Pdfreader(req *types.PdfRequest) (resp *types.PdfResponse, err error) {
	rp, err := http.Get(req.Url)
	if err != nil {
		return nil, err
	}

	defer rp.Body.Close()

	contents, err := l.client.ReadPdfUsingTika(l.ctx, rp.Body)
	if err != nil {
		return nil, err
	}
	items := make([]types.PdfItem, len(contents))
	err = copier.Copy(&items, &contents)
	if err != nil {
		return nil, err
	}
	resp = &types.PdfResponse{
		Data: items,
	}

	return
}
